package org.jaaksi.flutter.network

import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import org.jaaksi.library.FunctionBus

/** NetworkPlugin */
public class NetworkPlugin : FlutterPlugin, MethodCallHandler {
  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    val channel =
      MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "network_plugin")
    channel.setMethodCallHandler(NetworkPlugin())
  }

  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  companion object {
    @JvmStatic
    fun registerWith(registrar: Registrar) {
      val channel = MethodChannel(registrar.messenger(), "network_plugin")
      channel.setMethodCallHandler(NetworkPlugin())
    }
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    val url = call.argument<String>("path")
    val params = call.argument<Map<String, Any>>("params")

    when (call.method) {
      "rawGet" -> FunctionBus.getFunction(NetworkFunction::class.java)
        .rawGet(url!!, params, object : Callback<String> {
          override fun call(data: String?) {
            result.success(data)
          }
        })

      "rawPost" -> FunctionBus.getFunction(NetworkFunction::class.java)
        .rawPost(url!!, params, object : Callback<String> {
          override fun call(data: String?) {
            result.success(data)
          }
        })
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
  }
}
